package com.njg.juc.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @auther zzyybs@126.com
 * @Date 2025-04-24 8:24
 * @Description: 100个线程，每个线程加100次，求最后的number值
 */
public class CASDemo {
    private int number;

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
        ++number;
    }


    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.incrementAndGet();
    }

    AtomicInteger atomicInteger = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        CASDemo casDemo = new CASDemo();
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 100; j++) {
                        casDemo.setNumber();
                        casDemo.setAtomicInteger();
                        //业务逻辑
                    }
                    countDownLatch.countDown();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }, "A").start();

        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t" + casDemo.getNumber());
        System.out.println(Thread.currentThread().getName() + "\t" + casDemo.getAtomicInteger().get());


    }
}
